﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Magicodes.WeiChat.Infrastructure.MvcExtension.Ajax;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using Magicodes.WeiChat.Data;
using Magicodes.WeiChat.Data.Models.Site;
using System.Text.RegularExpressions;

namespace Magicodes.WeiChat.Controllers.Site
{
    public class Site_ArticleController : TenantBaseController<Site_Article>
    {

        // GET: Site_Article
        public async Task<ActionResult> Index(string q, Guid? type = null, int pageIndex = 1, int pageSize = 10)
        {
            if (!db.Site_ResourceTypes.Any(p => p.ResourceType == SiteResourceTypes.Article && p.IsSystemResource && p.Title == "默认"))
            {
                var article = new Site_ResourceType()
                {
                    Title = "默认",
                    IsSystemResource = true,
                    ResourceType = SiteResourceTypes.Article
                };
                SetModel(article, default(Guid));
                db.Site_ResourceTypes.Add(article);
                db.SaveChanges();
            }
            if (type == null)
            {
                var typeId = db.Site_ResourceTypes.Where(p => p.ResourceType == SiteResourceTypes.Article).First().Id;
                var model = new { type = typeId };
                if (!string.IsNullOrEmpty(Request.QueryString["lightLayout"]))
                {
                    return RedirectToAction("Index", new { type = typeId, lightLayout = 1 });
                }
                else
                {
                    return RedirectToAction("Index", new { type = typeId });
                }
            }
            ViewBag.ArticleTypes = db.Site_ResourceTypes.Where(p => p.ResourceType == SiteResourceTypes.Article).ToList();
            var queryable = db.Site_Articles.Include(s => s.CreateUser).AsQueryable();
            if (!string.IsNullOrWhiteSpace(q))
            {
                //请替换为相应的搜索逻辑
                queryable = queryable.Where(p => p.Content.Contains(q) || p.Name.Contains(q));
            }
            queryable = queryable.Where(p => p.ResourcesTypeId == type.Value);
            var pagedList = new PagedList<Site_Article>(
                             await queryable.OrderByDescending(p => p.CreateTime)
                             .Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(),
                             pageIndex, pageSize, queryable.Count());

            return View(pagedList);
        }

        // GET: Site_Article/Details/5
        public async Task<ActionResult> Details(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Site_Article site_Article = await db.Site_Articles.FindAsync(id);
            if (site_Article == null)
            {
                return HttpNotFound();
            }
            SetImgUrls(site_Article);
            return View(site_Article);
        }

        // GET: Site_Article/Create
        public ActionResult Create(Guid resourcesTypeId)
        {
            ViewBag.ResourcesTypeId = new SelectList(db.Site_ResourceTypes.Where(p => p.ResourceType == SiteResourceTypes.Article).ToList(), dataTextField: "Title", dataValueField: "Id", selectedValue: resourcesTypeId);
            return View();
        }

        // POST: Site_Article/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(enableValidation: false)]
        public async Task<ActionResult> Create([Bind(Include = "Id,Content,ResourcesTypeId,Summary,Name,SiteUrl,Url,CreateTime,OriginalUrl")] Site_Article site_Article)
        {
            if (ModelState.IsValid)
            {
                //site_Article.Content = site_Article.Content.Replace("\"", "'");
                SetImgUrls(site_Article);

                if (Encoding.Default.GetBytes(site_Article.Content).Length > 20000)
                {
                    ModelState.AddModelError("Content", "根据微信官方规定，内容不能超过20000个字符！");
                    return View(site_Article);
                }
                SetModel(site_Article, default(Guid));
                db.Site_Articles.Add(site_Article);
                await db.SaveChangesAsync();
                return RedirectToAction("Index", new { type = site_Article.ResourcesTypeId });
            }
            ViewBag.ResourcesTypeId = new SelectList(db.Site_ResourceTypes.Where(p => p.ResourceType == SiteResourceTypes.Article).ToList(), dataTextField: "Title", dataValueField: "Id", selectedValue: site_Article.ResourcesTypeId);
            return View(site_Article);
        }
        /// <summary>
        /// 处理图片路径
        /// </summary>
        /// <param name="site_Article"></param>
        /// <param name="isLoad">是否为本地显示（即替换为本地Site路径，否则替换为网络路径）</param>
        private void SetImgUrls(Site_Article site_Article, bool isLoad = false)
        {
            // 定义正则表达式用来匹配 img 标签   
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            // 搜索匹配的字符串   
            MatchCollection matches = regImg.Matches(site_Article.Content);
            var hostUrl = string.Format("{0}://{1}{2}/", Request.Url.Scheme, Request.Url.Host, Request.Url.Port == 80 ? "" : ":" + Request.Url.Port);
            int i = 0;
            // 取得匹配项列表   
            foreach (Match match in matches)
            {
                var url = match.Groups["imgUrl"].Value;
                if (string.IsNullOrWhiteSpace(url))
                    continue;
                if (!isLoad && !url.StartsWith(hostUrl))
                    continue;

                Site_Image img = null;
                if (isLoad)
                {
                    img = db.Site_Images.FirstOrDefault(p => p.Url == url);
                    site_Article.Content = site_Article.Content.Replace(url, hostUrl + img.SiteUrl);
                }
                else
                {
                    var siteUrl = url.Remove(0, hostUrl.Length);
                    img = db.Site_Images.FirstOrDefault(p => p.SiteUrl == siteUrl);
                    site_Article.Content = site_Article.Content.Replace(url, img.Url);
                }
            }
        }

        // GET: Site_Article/Edit/5
        public async Task<ActionResult> Edit(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Site_Article site_Article = await db.Site_Articles.FindAsync(id);
            if (site_Article == null)
            {
                return HttpNotFound();
            }
            SetImgUrls(site_Article, true);
            ViewBag.ResourcesTypeId = new SelectList(db.Site_ResourceTypes.Where(p => p.ResourceType == SiteResourceTypes.Article).ToList(), dataTextField: "Title", dataValueField: "Id", selectedValue: site_Article.ResourcesTypeId);
            return View(site_Article);
        }

        // POST: Site_Article/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(enableValidation: false)]
        public async Task<ActionResult> Edit([Bind(Include = "Id,Content,ResourcesTypeId,Summary,Name,SiteUrl,Url,CreateTime,OriginalUrl,TenantId")] Site_Article site_Article)
        {
            if (ModelState.IsValid)
            {
                SetImgUrls(site_Article);
                if (Encoding.Default.GetBytes(site_Article.Content).Length > 20000)
                {
                    ModelState.AddModelError("Content", "根据微信官方规定，内容不能超过20000个字符！");
                    return View(site_Article);
                }
                SetModelWithChangeStates(site_Article, site_Article.Id);
                await db.SaveChangesAsync();
                return RedirectToAction("Index", new { type = site_Article.ResourcesTypeId });
            }
            ViewBag.ResourcesTypeId = new SelectList(db.Site_ResourceTypes.Where(p => p.ResourceType == SiteResourceTypes.Article).ToList(), dataTextField: "Title", dataValueField: "Id", selectedValue: site_Article.ResourcesTypeId);
            return View(site_Article);
        }

        // GET: Site_Article/Delete/5
        public async Task<ActionResult> Delete(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Site_Article site_Article = await db.Site_Articles.FindAsync(id);
            if (site_Article == null)
            {
                return HttpNotFound();
            }
            ViewBag.ResourcesTypeId = new SelectList(db.Site_ResourceTypes.Where(p => p.ResourceType == SiteResourceTypes.Article).ToList(), dataTextField: "Title", dataValueField: "Id");
            return View(site_Article);
        }

        // POST: Site_Article/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(Guid? id)
        {
            Site_Article site_Article = await db.Site_Articles.FindAsync(id);
            db.Site_Articles.Remove(site_Article);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        // POST: Site_Article/BatchOperation/{operation}
        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="operation">操作方法</param>
        /// <param name="ids">主键集合</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Site_Article/BatchOperation/{operation}")]
        public async Task<ActionResult> BatchOperation(string operation, params Guid?[] ids)
        {
            var ajaxResponse = new AjaxResponse();
            if (ids.Length > 0)
            {
                try
                {
                    var models = await db.Site_Articles.Where(p => ids.Contains(p.Id)).ToListAsync();
                    if (models.Count == 0)
                    {
                        ajaxResponse.Success = false;
                        ajaxResponse.Message = "没有找到匹配的项，项已被删除或不存在！";
                        return Json(ajaxResponse);
                    }
                    switch (operation.ToUpper())
                    {
                        case "DELETE":
                            #region 删除
                            {
                                db.Site_Articles.RemoveRange(models);
                                await db.SaveChangesAsync();
                                ajaxResponse.Success = true;
                                ajaxResponse.Message = string.Format("已成功操作{0}项！", models.Count);
                                break;
                            }
                        #endregion
                        default:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    ajaxResponse.Success = false;
                    ajaxResponse.Message = ex.Message;
                }
            }
            else
            {
                ajaxResponse.Success = false;
                ajaxResponse.Message = "请至少选择一项！";
            }
            return Json(ajaxResponse);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
